﻿@inject IHttpService _httpService
@inject NavigationManager NavigationManager
@inject IDataCacheService _dataCacheService
@inject IEventService _eventService


<style>
    .m-rating .m-icon {
        padding: 0.1rem;
    }
</style>
<div class="rounded shadow-sm  bg-opacity mb-4">
    <div style="display: flex; justify-content: space-around; flex-wrap: wrap; " class="pt-4">

        <div class="ps-4 pe-4" style=" display: flex; max-width: 400px; width: 100%; align-items: center;">
            <MTextField Placeholder="可以搜索哦~" TValue="string" Value="@_dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.SearchString" ValueChanged="SearchValueChanged"  OnKeyDown="OnKeyDown" Class="pt-0"></MTextField>
        </div>
        <div class="ps-4 pe-4" style="max-width: 400px; width: 100%;">
            <CnGalWebSite.Components.Inputs.MasaSelecte Value="_dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.SortType" ValueChanged="SortValueChanged" TValue="JudgableGamesSortType" Class="pt-0" />
        </div>
        <div class="ps-4 pe-4" style="max-width: 400px; width: 100%;">
            <CnGalWebSite.Components.Inputs.MasaSelecte Value="_dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.DisplayType" ValueChanged="DisplayValueChanged" TValue="JudgableGamesDisplayType" Class="pt-0" />
        </div>
    </div>
</div>

<div class="row">
    @foreach (var item in Items.Skip((_dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.CurrentPage - 1) * _dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.MaxCount).Take(_dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.MaxCount))
    {
        <GameCard Model="item"  Type="_dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.DisplayType" OnClick="OnClickMore"/>
    }
</div>

@if (_dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.TotalPages > 1)
{
    <CnGalWebSite.Components.Paginations.MasaPagination Value="@_dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.CurrentPage" Length="@_dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.TotalPages" ValueChanged="OnPageClick" />
}

@if (Items.Any() == false && isReady)
{
    <NotFoundJudgableCard GameName="@_dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.SearchString" />
}

<CnGalWebSite.Shared.MasaComponent.PC.Entries.PlayedGames.OverviewDialog ShowNav @ref="overviewDialog" />


@code {
    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    List<JudgableGameViewModel> Items = new List<JudgableGameViewModel>();

    CnGalWebSite.Shared.MasaComponent.PC.Entries.PlayedGames.OverviewDialog overviewDialog;
    JudgableGameViewModel currentGame;

    bool isReady;

    protected override async Task OnInitializedAsync()
    {

        await Refresh();
        isReady = true;
    }

    public async Task Refresh()
    {
        try
        {
            if (_dataCacheService.JudgableGamesCatche.Count == 0)
            {
                _dataCacheService.JudgableGamesCatche = await _httpService.GetAsync<List<JudgableGameViewModel>>("api/anniversaries/GetAllJudgableGames");
            }

            var searchString = _dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.SearchString;
            if (string.IsNullOrWhiteSpace(searchString))
            {
                Items = _dataCacheService.JudgableGamesCatche;
            }
            else
            {
                Items = _dataCacheService.JudgableGamesCatche.Where(s => (s.Name?.Contains(searchString) ?? false) || (string.IsNullOrWhiteSpace(s.Name) == false && (searchString?.Contains(s.Name) ?? false)) ||
                          (s.BriefIntroduction?.Contains(searchString) ?? false) || (string.IsNullOrWhiteSpace(s.BriefIntroduction) == false && (searchString?.Contains(s.BriefIntroduction) ?? false)))
                           .ToList();
            }


            Items = _dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.SortType switch
            {
                JudgableGamesSortType.LastScoreTime => Items.OrderByDescending(s => s.LastScoreTime).ToList(),
                JudgableGamesSortType.PublishTime => Items.OrderByDescending(s => s.PublishTime).ToList(),
                JudgableGamesSortType.Random => Items.Random(),
                JudgableGamesSortType.ScoreCount => Items.OrderByDescending(s => s.ScoreCount).ToList(),
                JudgableGamesSortType.LastEditTime => Items.OrderByDescending(s => s.LastEditTime).ToList(),
                JudgableGamesSortType.ReadCount => Items.OrderByDescending(s => s.ReaderCount).ToList(),
                _ => Items
            };

            _dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.Count = Items.Count;
            _dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.CurrentPage = 1;

        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "获取可评选的游戏列表失败");
        }
    }


    public async Task SortValueChanged(JudgableGamesSortType type)
    {
        _dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.SortType = type;
        _eventService.OnSavaTheme();
        await Refresh();
    }
    public async Task DisplayValueChanged(JudgableGamesDisplayType type)
    {
        _dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.DisplayType = type;
        _eventService.OnSavaTheme();
        await Refresh();
    }


    public async Task SearchValueChanged(string str)
    {
        _dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.SearchString = str;
        _eventService.OnSavaTheme();
        await Refresh();
    }

    private async Task OnKeyDown(KeyboardEventArgs e)
    {
        if (e.Code == "Enter" || e.Code == "NumpadEnter")
        {
            await Refresh();
        }
    }

    private void OnPageClick(int pageIndex)
    {
        _dataCacheService.ThemeSetting.AnniversariesSetting.JudgableGamesSetting.CurrentPage = pageIndex;
        _eventService.OnSavaTheme();
        StateHasChanged();

    }

    public async Task OnClickMore(JudgableGameViewModel model)
    {
        currentGame = model;
        if (overviewDialog != null)
        {
            try
            {
                var temp = await _dataCacheService.PlayedGameOverviewDataCatche.GetCache(model.Id.ToString());
                temp.UserScores.Random();
                await overviewDialog.Refresh(true, temp);
            }
            catch (Exception ex)
            {
                await ErrorHandler.ProcessError(ex, $"获取评分概览数据失败");
            }


        }
    }

}
